package com.onegroup.common.utils;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author: 曾雪斌
 * @Description:
 * @History:
 */
public class JwtUtil {

    // 有效期设置为一小时
    public static final Long JWT_TTL = 60 * 60 * 1000L;
    // 设置密钥明文
    public static final String JWT_KEY = "onegroup";

    public static String getUuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成加密后的密钥 secretKey
     * @return key
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }

        long expMillis = nowMillis + ttlMillis;
        Date expDate= new Date(expMillis);

        return Jwts.builder()
                // 唯一的id
                .setId(uuid)
                // 主题，可以是json数据
                .setSubject(subject)
                // 签发者
                .setIssuer("onegroup")
                .setIssuedAt(now)
                // 使用HS256对称加密算法签名，第二个参数为密钥
                .signWith(signatureAlgorithm, secretKey)
                .setExpiration(expDate);
    }

    /**
     * 生成jwt
     * @param subject token存放的数据(json格式)
     * @return jwt
     */
    public static String createJwt(String subject) {
        // 设置过期时间
        JwtBuilder builder = getJwtBuilder(subject, null, getUuid());
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param subject token存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return jwt
     */
    public static String createJwt(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUuid());
        return builder.compact();
    }

    /**
     * 创建token
     * @param id uuid
     * @param subject token存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return token
     */
    public static String createJwt(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    /**
     * 解析jwt
     * @param jwt 令牌
     * @return jwt
     */
    public static Claims parseJwt(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
